from datetime import datetime
from datetime import timedelta
import Dao

class BookProcessor:

	def __init__(self):
		""" default constructor """
		self._dao = Dao.Dao()
		self._libraryDoc = self._dao.getLibraryDoc()
		self._bookDictionary = self._dao.getBookDictionary()
		
	def checkoutBook(self, bookid):
		""" check out a book from the library """
		currTime = datetime.now()
		returnDate = currTime + timedelta(3)
		
		lastBookId = self._libraryDoc.getElementsByTagName('bookid')[-1].firstChild.data
		#if int(bookid) > int(lastBookId):
		#	return False
			
		book = self._bookDictionary[bookid]
		if book.isAvailable():
			book.setAvailable(False)
			book.setReturnDate(returnDate)
			return True
		else:
			return False
			
	def returnBook(self, bookid):
		""" return a book to the library """
		
		lastBookId = self._libraryDoc.getElementsByTagName('bookid')[-1].firstChild.data
		#if int(bookid) > int(lastBookId):
		#	return false
			
		book = self._bookDictionary[bookid]
		
		if book.isAvailable():
			return False
		else:
			book.setAvailable(True)
			return True
		
	def searchBook(self, title="", author="", isbn="", category="", keyword=""):
		""" search a book, will return a list of dictionaries"""
		resultList={}
				
		# if title is not empty, search by Title
		if title != "":
			titles = self._libraryDoc.getElementsByTagName('title')
			for t in titles:
				if t == title:
					return
	
		if keyword != "":
			bookIdList=[]
			#get all the bookid filds from xml dom
			BookIdElements = self._libraryDoc.getElementsByTagName('bookid')
			for bookIds in BookIdElements:
				bookIdList.append(bookIds.firstChild.data)
			
			#traverse through bookdictionary using bookid fields
			for books in bookIdList:
				if self._bookDictionary[books].getBookId().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
				elif self._bookDictionary[books].getTitle().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
				elif self._bookDictionary[books].getAuthor().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
				elif self._bookDictionary[books].getIsbn().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
				elif self._bookDictionary[books].getCategory().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
				elif self._bookDictionary[books].getKeyword().upper().count(keyword.upper()) >=1:
					resultList[books]=self._bookDictionary[books]
			if resultList:
				return resultList		
			#see if keyword can be found in any of the fields
			#if found then add book to found list of books
			#return list of books found
			

	def getBookDictionary(self):
		return self._bookDictionary